package com.chaodev.base.controller;

import com.github.pagehelper.PageInfo;
import com.chaodev.base.model.*;
import com.chaodev.base.base.RedisDao;
import com.chaodev.base.dto.DepartDTO;
import com.chaodev.base.dto.NoticeDTO;
import com.chaodev.base.dto.RoleDTO;
import com.chaodev.base.service.IDepartService;
import com.chaodev.base.service.IRoleService;
import com.chaodev.base.utils.JwtUtil;
import com.chaodev.base.service.ILogService;
import com.chaodev.base.service.INoticeService;

import com.chaodev.base.utils.TreeHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@SuppressWarnings("all")
@RestController
@RequestMapping(value = "/notice")
@Api(value = "公告管理")
public class NoticeController {
    @Autowired
    INoticeService noticeService;
    @Autowired
    RedisDao redisDao;
    @Autowired
    ILogService logService;
    @Autowired
    IDepartService departService;
    @Autowired
    IRoleService roleService;

    @Value("${platform}")
    private String platform;

    @PostMapping(value = "/NoticeList", consumes = {"application/json"})
    @ApiOperation(value = "公告列表")
    public Result NoticeList(@RequestBody DataPageVO dataPage, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        try {
            if (redisDao.existsKey(token)) {
                userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
                //设置默认排序方式
                if (null == dataPage.getOrder() || "".equals(dataPage.getOrder())) {
                    dataPage.setOrder("DESC");
                }
                //设置默认排序参数方式
                if (null == dataPage.getSort() || "".equals(dataPage.getSort())) {
                    dataPage.setSort("createTime");
                }
                Map<String, Object> map = new HashMap<>();
                map.put("P_PAGE", dataPage.getPage());
                map.put("P_PAGESIZE", dataPage.getRows());
                map.put("P_KEYWORD", dataPage.getKeyword());
                map.put("P_SORTNAME", dataPage.getSort());
                map.put("P_SORTORDER", dataPage.getOrder());
                // 停用已超有效期的数据
                noticeService.noticeTimeout();
                // 获取公告列表
                PageInfo<NoticeDTO> noticelist = noticeService.noticeList(map);
                Map<String, Object> reMap = new HashMap<>();
                reMap.put("total", noticelist.getTotal());
                reMap.put("rows", noticelist.getList());
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setData(reMap);
                Result logResult = new Result();
                logResult.setCode(0);
                logResult.setMsg("数据获取成功");//不记录返回数据，只做标识
                logResult.setServerID(result.getServerID());
                logService.logAdd(dataPage.toString(), "公告列表", "SUCCESS", logResult.toString(), userInfo, request);
            } else {
                result.setCode(-1);
                result.setMsg("登录超时");
                logService.logAdd(dataPage.toString(), "公告列表", "ERROR", result.toString(), userInfo, request);
            }
        } catch (Exception e) {
            result.setCode(-1);
            result.setMsg("获取失败");
            logService.addErrorLog(request, e.getMessage().toString(), "");
        }
        return result;
    }

    @PostMapping(value = "/save")
    @ResponseBody
    @ApiOperation(value = "公告新增/编辑")
    @Transactional(rollbackFor = Exception.class)
    public Result NoticeAdd(@RequestBody Notice notice, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        try {
            if (redisDao.existsKey(token)) {
                userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
                notice.setCreateUser(userInfo.getUserId());
                boolean flag, flag1 = false, flag2 = false;
                if ("".equals(notice.getId()) || notice.getId() == null) {
                    // 新增公告
                    if ("mysql".equals(platform)) {
                        // mysql 获取自增主键
                        flag = noticeService.noticeAddMysql(notice);
                    } else {
                        // oracle 获取自增主键
                        flag = noticeService.noticeAddOracle(notice);
                    }
                    // 添加部门
                    if ("".equals(notice.getDeparts()) || notice.getDeparts() == null) {
                        flag1 = true;
                    } else {
                        flag1 = noticeService.noticeDepartAdd(notice);
                    }
                    // 添加角色
                    if ("".equals(notice.getRoles()) || notice.getRoles() == null) {
                        flag2 = true;
                    } else {
                        flag2 = noticeService.noticeRoleAdd(notice);
                    }
                } else {
                    // 修改公告
                    flag = noticeService.noticeUpdate(notice);
                    if ("".equals(notice.getDeparts()) || notice.getDeparts() == null) {
                        flag1 = true;
                    } else {
                        // 先吧部门状态置位0再插入
                        flag1 = noticeService.noticeDepartUpdate(notice);
                    }
                    if ("".equals(notice.getRoles()) || notice.getRoles() == null) {
                        flag2 = true;
                    } else {
                        // 先把角色状态置为0再插入
                        flag2 = noticeService.noticeRoleUpdate(notice);
                    }
                }
                if (((flag == flag1) == flag2) == true) {
                    result.setCode(ResultEnum.SUCCESS.getCode());
                    result.setMsg("提交成功");
                } else {
                    result.setCode(-1);
                    result.setMsg("提交失败");
                }
                logService.logAdd(notice.toString(), "公告新增/编辑", "SUCCESS", result.toString(), userInfo, request);
            } else {
                result.setCode(-1);
                result.setMsg("登录超时");
                logService.logAdd(notice.toString(), "公告新增/编辑", "ERROR", result.toString(), userInfo, request);
            }
        } catch (Exception e) {
            result.setCode(-1);
            result.setMsg("提交失败");
            logService.addErrorLog(request, e.getMessage().toString(), "");
        }
        return result;
    }

    @PostMapping(value = "/NoticeUpd")
    @ResponseBody
    @ApiOperation(value = "公告启用")
    @Transactional(rollbackFor = Exception.class)
    public Result NoticeUpd(@RequestBody Notice notice, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            notice.setCreateUser(userInfo.getUserId());
            boolean flag = false;
            // 1启用，5上架，-1停用
            if ("1".equals(notice.getState()) || "11".equals(notice.getState()) || "5".equals(notice.getState())) {
                flag = noticeService.noticeUpd(notice);
            }
            if (flag == true) {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("操作成功");
            } else {
                result.setCode(-1);
                result.setMsg("操作失败");
            }
            logService.logAdd(notice.toString(), "公告启用/停用/发布", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(notice.toString(), "公告启用/停用/发布", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping(value = "/delete")
    @ResponseBody
    @ApiOperation(value = "公告删除")
    @Transactional(rollbackFor = Exception.class)
    public Result NoticeDel(@RequestBody Notice notice, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            notice.setCreateUser(userInfo.getUserId());
            boolean flag, flag1, flag2 = false;
            // 删除部门
            noticeService.noticeDepartDel(notice);
            // 删除角色
            flag2 = noticeService.noticeRoleDel(notice);
            flag = noticeService.noticeDel(notice);
            if (flag == true) {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("删除成功");
            } else {
                result.setCode(-1);
                result.setMsg("删除失败");
            }
            logService.logAdd(notice.toString(), "公告删除", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(notice.toString(), "公告删除", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping(value = "/NoticeListHome")
    @ResponseBody
    @ApiOperation(value = "公告列表首页")
    public Result NoticeListWeb(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        try {
            if (redisDao.existsKey(token)) {
                userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
                Map<String, Object> map = new HashMap<>();
                map.put("USER_ID", userInfo.getUserId());
                map.put("DEPART_ID", userInfo.getDepartId());
                map.put("ROLE_ID", userInfo.getRoleId());
                ArrayList<Notice> data = noticeService.noticeListWeb(map);
                result.setCode(0);
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setData(data);
                Result logResult = new Result();
                logResult.setCode(0);
                logResult.setMsg("数据获取成功");//不记录返回数据，只做标识
                logResult.setServerID(result.getServerID());
                logService.logAdd("", "公告首页列表", "SUCCESS", logResult.toString(), userInfo, request);
            } else {
                result.setCode(-1);
                result.setMsg("登录超时");
                logService.logAdd("", "公告首页列表", "ERROR", result.toString(), userInfo, request);
            }
        } catch (Exception e) {
            result.setCode(-1);
            result.setMsg("获取失败");
            logService.addErrorLog(request, e.getMessage().toString(), "");
        }
        return result;
    }

    @PostMapping(value = "/getDepartTreeList")
    @ApiOperation(value = "部门树形列表")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result departTreeList(@RequestBody @ApiParam(value = "字典类型") DictDetail dictDetail, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            Map<String, Object> map = new HashMap<>();
            map.put("P_PAGE", 1);
            map.put("P_PAGESIZE", 999);
            map.put("P_KEYWORD", "");
            map.put("P_USERID", userInfo.getUserId());
            map.put("U_DEPART_ID", userInfo.getDepartId());
            map.put("V_KEYWORD", "");
            List<DepartDTO> departList = departService.departQuery(map).getList();
            List<ElementTreeModel> elementTreeModelList = new ArrayList<>();
            if (!departList.isEmpty()) {
                for (DepartDTO item : departList) {
                    ElementTreeModel model = new ElementTreeModel();
                    model.setId(item.getDepartId());
                    model.setParentId(item.getParentDepartId());
                    model.setValue(item.getDepartId());
                    model.setLabel(item.getDepartName());
                    elementTreeModelList.add(model);
                }
                elementTreeModelList = TreeHelper.getElementTreeInfo(elementTreeModelList);
            }
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setData(elementTreeModelList);
            result.setCode(0);
            //记录日志
            Result logResult = new Result();
            logResult.setCode(0);
            //不记录返回数据，只做标识
            logResult.setMsg("数据获取成功");
            logResult.setServerID(result.getServerID());
            logService.logAdd(dictDetail.toString(), "字典项列表", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(dictDetail.toString(), "字典项列表", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping(value = "/getRoleTreeList")
    @ApiOperation(value = "角色树形列表")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result roleTreeList(@RequestBody @ApiParam(value = "字典类型") DictDetail dictDetail, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            Map<String, Object> map = new HashMap<>();
            map.put("P_PAGE", 1);
            map.put("P_PAGESIZE", 999);
            map.put("P_KEYWORD", "");
            map.put("P_USERID", userInfo.getUserId());
            map.put("U_ROLE_ID", userInfo.getRoleId());
            List<RoleDTO> roleList = roleService.roleQuery(map).getList();
            List<ElementTreeModel> elementTreeModelList = new ArrayList<>();
            if (!roleList.isEmpty()) {
                for (RoleDTO item : roleList) {
                    ElementTreeModel model = new ElementTreeModel();
                    model.setId(item.getRoleId());
                    model.setParentId(item.getParentRoleId().toString());
                    model.setValue(item.getRoleId());
                    model.setLabel(item.getRoleName());
                    elementTreeModelList.add(model);
                }
                elementTreeModelList = TreeHelper.getElementTreeInfo(elementTreeModelList);
            }
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setData(elementTreeModelList);
            result.setCode(0);
            //记录日志
            Result logResult = new Result();
            logResult.setCode(0);
            //不记录返回数据，只做标识
            logResult.setMsg("数据获取成功");
            logResult.setServerID(result.getServerID());
            logService.logAdd(dictDetail.toString(), "字典项列表", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(dictDetail.toString(), "字典项列表", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping(value = "/getUserNoticeList")
    @ApiOperation(value = "获取当前用户消息列表")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result getUserNoticeList( HttpServletRequest request, HttpServletResponse response){
        Result result = new Result();
        String token = request.getHeader("token");
        Result logResult = new Result();
        UserInfo userInfo = new UserInfo();
        try {
            if (!redisDao.existsKey(token)) {
                result.setCode(ResultEnum.EREOR.getCode());
                result.setMsg("登录超时");
                return result;
            }
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            Map<String, Object> map = new HashMap<>();
            map.put("USER_CODE", userInfo.getUserId());
            map.put("DEPART_ID", userInfo.getDepartId());
            map.put("ROLE_ID", userInfo.getRoleId());

            result.setData(noticeService.userNoticeList(map));
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setMsg("查询成功");
        } catch (Exception exception) {
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg("发生错误:" + exception.getMessage());
        } finally {
            BeanUtils.copyProperties(result, logResult);
            logResult.setData(null);
            String resultCode = logResult.getCode().equals(ResultEnum.SUCCESS.getCode()) ? "SUCCESS" : "ERROR";
            logService.logAdd("", "获取当前用户消息列表", resultCode, logResult.toString(), userInfo, request);
        }
        return result;
    }

}